import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fwanandroid/model/api/WanAndroidService.dart';
import 'package:fwanandroid/provider/UserState.dart';
import 'package:fwanandroid/ui/views/CommonAppBar.dart';
import 'package:fwanandroid/utils/ToastUtil.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';
import '../MyColors.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool _isObscure = true;
  bool _canLogin = false;
  String username = "";
  String password = "";
  FocusNode focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonAppBar(title: "登录"),
      body: Column(
        children: [
          buildLoginTextField(
              hintText: "用户名",
              onChange: (value) {
                username = value;
                setState(() {
                  _canLogin = (password.isNotEmpty && username.isNotEmpty)
                      ? true
                      : false;
                });
              }),
          buildLoginTextField(
              hintText: "密码",
              obscureText: _isObscure,
              suffixIcon: IconButton(
                icon:
                    Icon(_isObscure ? Icons.visibility_off : Icons.visibility),
                onPressed: () {
                  setState(() {
                    _isObscure = !_isObscure;
                  });
                },
              ),
              onChange: (value) {
                password = value;
                setState(() {
                  _canLogin =
                  (password.isNotEmpty && username.isNotEmpty) ? true : false;
                });
              }),
          const SizedBox(
            height: 16,
          ),
          buildLoginBtnWidget("登录", () {
            doLogin(context);
          }),
          buildLoginBtnWidget("注册"),
        ],
      ),
    );
  }

  // ---------------- 创建组件

  Widget buildLoginBtnWidget(String title, [Function? clickListner]) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
      child: InkWell(
        onTap: () {
          clickListner ?? ();
        },
        child: Container(
          height: 48,
          decoration: BoxDecoration(
              color: _canLogin ? MyColors.leiMuBlue : Colors.grey[300]),
          width: MediaQuery.of(context).size.width,
          child: Center(
            child: Text(
              title,
              style: const TextStyle(color: Colors.white, fontSize: 16),
            ),
          ),
        ),
      ),
    );
  }

  Widget buildLoginTextField(
      {String hintText = "",
      bool obscureText = false,
      Widget? suffixIcon,
      onChange}) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
      child: TextField(
        obscureText: obscureText,
        decoration: InputDecoration(
          hintText: hintText,
          border: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.grey)),
          focusedBorder: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.black)),
          suffixIcon: suffixIcon,
        ),
        maxLines: 1,
        onChanged: (value) {
          onChange(value);
        },
      ),
    );
  }

  // ---------------- 请求数据

  doLogin(BuildContext context) {
    FocusScope.of(context).requestFocus(focusNode);
    EasyLoading.show(status: 'loading...');
    WanAndroidService.login(username, password).then((result) {
      UserState userState = Provider.of<UserState>(context, listen: false);
      userState.updateUser(result);
      ToastUtil.show("登录成功");
      Navigator.pop(context);
    }).catchError((error) {
      Logger().d("登录失败${error.toString()}");
      ToastUtil.showByError(error);
    }).whenComplete(() {
      EasyLoading.dismiss();
    });
  }
}
